<template>
	<a-modal
		:centered="true"
		class="boxes-info-device-name"
		:body-style="{ padding: '40px 32px' }"
		:open="props.visible"
		width="416px"
		:confirm-loading="loading"
		:closable="false"
		ok-text="更改"
		@cancel="onClose"
		@ok="onSubmitName"
	>
		<a-form ref="nameFormRef" class="name-form" :model="nameForm" layout="vertical">
			<a-form-item label="设备名称" class="hide-required" name="boxName" :rules="[{ required: true, message: '请输入设备名称' }]">
				<a-input v-model:value.trim="nameForm.boxName" placeholder="请输入设备名称" :maxlength="10" />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup lang="ts" name="BoxInfoDeviceName">
import { FormInstance } from 'ant-design-vue';
import { g6RegValidate } from 'glasssix-utils-ts';
import { BoxManageApi } from '../../../api';

type _Props = {
	visible: boolean;
	id: string;
	boxName: string;
};
const props = withDefaults(defineProps<_Props>(), {
	visible: false,
	id: '',
	boxName: ''
});

const emits = defineEmits<{
	(e: 'close'): void;
	(e: 'ok'): void;
}>();

const $message: any = inject('$message');

const nameFormRef = ref<FormInstance>();
const nameForm = reactive({
	boxName: ''
});

const watchStop = watch(
	() => props.visible,
	(visible) => {
		if (visible) {
			console.log('获取名称：', props.boxName);
			nameForm.boxName = props.boxName;
		}
	}
);

const loading = ref<boolean>(false);
const onClose = (): void => {
	nameFormRef.value?.resetFields();
	emits('close');
};
const onSubmitName = async (): Promise<void> => {
	g6RegValidate.formSubmit(nameFormRef.value, async () => {
		try {
			loading.value = true;
			const param = { id: props.id, ...nameForm };
			const res: TsRes = await BoxManageApi.updateBoxName({ ...param });
			if (res?.code === 0) {
				$message.success('操作成功');
				onClose();
				emits('ok');
			}
		} catch (error) {
		} finally {
			loading.value = false;
		}
	});
};
onUnmounted(() => {
	watchStop();
});
</script>

<style lang="less" scoped>
// 弹窗
.boxes-info-device-name {
	.name-form {
		.ant-form-item-required {
			&::after {
				display: none;
			}
		}
	}
}
</style>
